package org.bigdata.framework.admin.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.bigdata.framework.core.model.Classes;
import org.bigdata.framework.core.model.DataBackup;
import org.bigdata.framework.core.model.DataHandling;
import org.bigdata.framework.core.model.DataRecovery;
import org.bigdata.framework.core.model.Log;
import org.bigdata.framework.core.model.Member;
import org.bigdata.framework.core.model.ShardingRepositoryCount;
import org.bigdata.framework.core.model.User;
import org.apache.commons.io.FileUtils;
import org.bigdata.framework.admin.web.util.CreateXMLFile;
import org.bigdata.framework.admin.web.util.DateUtils;
import org.bigdata.framework.admin.web.util.FileDownloadUtil;
import org.bigdata.framework.admin.web.util.FileTool;
import org.bigdata.framework.core.model.DataSource;
import org.bigdata.framework.core.model.Dict;
import org.bigdata.framework.core.model.DictItem;
import org.bigdata.framework.core.protocol.IBaseService;
import org.bigdata.framework.core.protocol.IDataHandlingService;
import org.bigdata.framework.core.protocol.IDynamicService;
import org.bigdata.framework.core.protocol.IPublicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.xxl.conf.core.XxlConfClient;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.dao.IXxlJobInfoDao;


@Controller
public class DataHandlingController extends BaseContoroller{
	
	@Autowired
	private IBaseService baseService;

	@Autowired
	private IPublicService publicService;
	
	@Autowired
	private IDataHandlingService dataHandlingService;
	
	@Autowired
	private IDynamicService dynamicService;

	
	@Autowired
	private IXxlJobInfoDao xxlJobInfoDao;
	// 公共日常记录
	public void Log(Integer createUserId, String logType, String classesId,
			String dataId, String logText, Integer logStatus) throws Exception {
		// 获得本机IP
		InetAddress addr = InetAddress.getLocalHost();
		String createIpAddress = addr.getHostAddress();
		// 获得时间
		String createTime = DateUtils.getDateTime();
		
		Log log = new Log();
		log.setCreateTime(createTime);
		log.setCreateUserId(createUserId);
		log.setCreateIpAddress(createIpAddress);
		log.setLogType(logType);
		log.setLogText(logText);
		log.setLogStatus(logStatus);
	
		if (classesId != null) {
			log.setClassesId(classesId);
		}
		if (dataId != null) {
			log.setDataId(dataId);
		}
		baseService.saveLog(log);
	}
	
	// 数据源列表
	@RequestMapping("user-data-handling-source-list.html")
	public String toDataHandlingSourceList() {
		return "/modules/datahandling/data_handling_source_list";
	}
	// 数据源 新增修改 管理
	@RequestMapping("data-handling-source-addEntity.html")
	public String toDataHandlingSourceaddEdit() {
		return "/modules/datahandling/data_handling_source_addEntity";
	}
	// 数据源导入列表
	@RequestMapping("data-handling-import-list.html")
	public String toDataHandlingImportList() {
		return "/modules/datahandling/data_handling_import_list";
	}
	// 新建导入源列表
	@RequestMapping("data-handling-import-from.html")
	public String toDataImportFrom() {
		
		return "/modules/datahandling/data_handling_import_from";
	}
	// 新建导入源列表2
	@RequestMapping("data-handling-import-from2.html")
	public String toDataImportFrom2(Model model) {
		model.addAttribute("systemName", "store");
		return "/modules/datahandling/data_handling_import_from2";
	}
	// 新建数据源列表
	@RequestMapping("data-handling-import-source-from.html")
	public String toDataHandlingImportSourceFrom() {
		return "/modules/datahandling/data_handling_import_source_list";
	}

	// 数据源导出列表
	@RequestMapping("data-handling-export-list.html")
	public String toDataHandlingExportList() {
		return "/modules/datahandling/data_handling_export_list";
	}
	// 新建数据源导出
	@RequestMapping("data-handling-export-to.html")
	public String toDataExportTo(Model model) {
		model.addAttribute("systemName", "store");
		return "/modules/datahandling/data_handling_export_to";
	}
	// 弹出粘贴对应关系页
	@RequestMapping("data-handling-import-toPaste.html")
	public String toPaste(Model model) {
		return "/modules/datahandling/data_handling_import_toPaste";
	}
	
	//数据源管理
	@RequestMapping("findallDataHandlingSource")
	@ResponseBody
	public void tofindAllDataHandlingSource(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer pageNumber = Integer.parseInt(request
				.getParameter("pageNumber"));
		Integer pageSize = 1;
		if (request.getParameter("page") != null) {
			pageSize = Integer.parseInt(request.getParameter("page"));
		} else {
			pageSize = 1;
		}
		String queryParam = request.getParameter("queryParams");

		String text = request.getParameter("text");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if(text != null && !"".equals(text)){
			queryParams.put("%,"+queryParam, text);
		}
		int count = publicService.getDataSourceCount(queryParams);
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		List<DataSource> list = publicService.getDataSource(queryParams,
				pageSize, pageNumber);
		for (int i = 0; i < (list==null?0:list.size()); i++) {
			DataSource dataSource = list.get(i);
			if (dataSource != null) {
				mp = new LinkedHashMap<String, Object>();
				mp.put("id", dataSource.getId());
				mp.put("name", dataSource.getName());
				mp.put("description", dataSource.getDescription());
				mp.put("sourceType", dataSource.getSourceType());
				mp.put("url", dataSource.getUrl());
				mp.put("user", dataSource.getUser());
				mp.put("password", dataSource.getPassword());
				mp.put("coding", dataSource.getCoding());
				if (dataSource.getStatus() == 1) {
					mp.put("classYangShi", "label-success");
					mp.put("status", "可使用");
				} else if (dataSource.getStatus() == 2) {
					mp.put("classYangShi", "btn-danger");
					mp.put("status", "禁 &nbsp;&nbsp;用 ");
				}
				r.add(mp);
			}
		}
		String result = formatToJson(r);
		StringBuffer sb = new StringBuffer();
		int listsize = list==null?0:list.size();
		sb.append("{\"listsize\":" + listsize + ",");
		sb.append("\"pageSize\":"
				+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}
	
	// 插入 更新 数据源 数据
	@RequestMapping("addEditDataHandlingSource")
	@ResponseBody
	public void toaddEditDataHandlingSource(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String description = request.getParameter("description");
		String sourceType = request.getParameter("sourceType");
		String url = request.getParameter("url");
		String user = request.getParameter("user");
		String password = request.getParameter("password");
		String coding = request.getParameter("coding");
		int status = Integer.parseInt(request.getParameter("status"));
		User logUser = publicService.findUser((Integer) request.getSession()
				.getAttribute("userid"));
		DataSource dataSource = new DataSource();
		dataSource.setName(name);
		dataSource.setDescription(description);
		dataSource.setSourceType(sourceType);
		dataSource.setUrl(url);
		dataSource.setUser(user);
		dataSource.setPassword(password);
		dataSource.setStatus(status);
		dataSource.setCoding(coding);
		DataSource d2 = new DataSource();
		if (!id.equals("0") && !id.equals("0") && id != null) {
			dataSource.setId(Integer.parseInt(id));
			DataSource logDataSource = publicService.findDataSource(Integer
					.parseInt(id));
			int logTime = 0;
			try {
				d2 = baseService.editDataSource(dataSource);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null,
						"【" + logUser.getNickname() + "】【修改】数据源【"
								+ logDataSource.getName() + "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null,
						"【" + logUser.getNickname() + "】【修改】数据源【"
								+ logDataSource.getName() + "】成功！修改为【" + name
								+ "】", 0);
			}
		} else if (id.equals("0")) {
			int logTime = 0;
			try {
				d2 = baseService.saveDataSource(dataSource);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】数据源【" + name
						+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】数据源【" + name + "】成功！",
						0);
			}

		}
		String result = formatToJson(d2);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	// 导出资源
	@RequestMapping("exportDataHandlingData")
	public void exportDataHandlingData(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		DataHandling dataHandling = dataHandlingService.findDataHandling(Integer.parseInt(id));
		String downloadPath = dataHandling.getDownloadPath();
		Classes classes = publicService.findClasses(dataHandling.getClassesId());
		String title = downloadPath.substring(downloadPath.lastIndexOf("."), downloadPath.length());
		FileDownloadUtil.download(downloadPath, classes.getNameZh()+title, request, response);

		

	}
	// 获取数据源更新内容
	@RequestMapping("dataHandlingSourceEditShow")
	@ResponseBody
	public void toDataHandlingSourceEditShow(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer id = Integer.parseInt(request.getParameter("id"));
		HashMap<String, Object> dMap = new HashMap<String, Object>();
		DataSource dataSource = publicService.findDataSource(id);
		if (dataSource != null) {
			dMap.put("id", dataSource.getId());
			dMap.put("name", dataSource.getName());
			dMap.put("description", dataSource.getDescription());
			dMap.put("sourceType", dataSource.getSourceType());
			dMap.put("url", dataSource.getUrl());
			dMap.put("user", dataSource.getUser());
			dMap.put("password", dataSource.getPassword());
			dMap.put("status", dataSource.getStatus());
			dMap.put("coding", dataSource.getCoding());
		}
		String result = formatToJson(dMap);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	// 测试数据源
	@ResponseBody
	@RequestMapping("dataHandlingSourceConnectionTest")
	public void toDataHandlingSourceConnectionTest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		HashMap<String, Object> dMap = new HashMap<String, Object>();
		
		String sourceType = request.getParameter("sourceType");//数据源类型
		String url = request.getParameter("url");//数据源链接
		String user = request.getParameter("user");//数据源用户名
		String password = request.getParameter("password");//数据源数据库密码
		String coding = request.getParameter("coding");//数据源的编码，链接access需要

		boolean connctionTest = dataHandlingService.getConnectionTest(url, user, password, coding, sourceType);
		if(connctionTest){
			dMap.put("info", 1);
		}else{
			dMap.put("info", 0);
		}
		
		String result = formatToJson(dMap);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	// 数据导入列表查询
	@RequestMapping("DataHandlingList")
	@ResponseBody
	public void toDataHandlingList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
		Integer pageSize = Integer.parseInt(request.getParameter("page"));
		String queryParam = request.getParameter("queryParams");
		String type = request.getParameter("type");
		String text = request.getParameter("text");
		//访问前缀	
		String uploadPath =  XxlConfClient.get("dal.file.server", "") +"/";
		//磁盘前缀
		String adjunctPath =  XxlConfClient.get("dal.file.path", "");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if(text != null && !"".equals(text)){
			queryParams.put("%,"+queryParam, text);
		}
		if(type != null && !"".equals(type)){
			queryParams.put("%,type", type);
		}
		queryParams.put("^,createTime", "desc");
		int count = dataHandlingService.getDataHandlingCount(queryParams);
		List<DataHandling> list = dataHandlingService.getDataHandling(queryParams,pageSize, pageNumber);
		for (int i = 0; i < list.size(); i++) {
			DataHandling dataHandling = list.get(i);
			String downloadPath = dataHandling.getDownloadPath();
			if(null != downloadPath && !"".equals(downloadPath)){
				String newDownloadPath = downloadPath.replaceAll(adjunctPath, "");
				dataHandling.setDownloadPath(uploadPath+newDownloadPath);
			}
		}
		List<DataSource> dataSource = publicService.getDataSource();
		List<Classes> classes = publicService.getClasses();
		String result = formatToJson(list);
		String rdataSource = formatToJson(dataSource);
		String rclasses = formatToJson(classes);
		StringBuffer sb = new StringBuffer();
		int listsize = list==null?0:list.size();
		sb.append("{\"listsize\":" + listsize + ",");
		sb.append("\"pageSize\":"
				+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"result\":" + result+",");
		sb.append("\"rdataSource\":" + rdataSource+",");
		sb.append("\"rclasses\":" + rclasses);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}
	//获取数据库表名
	@RequestMapping("DataHandlingTableName")
	@ResponseBody
	public void todataHandlingTableName(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer id = Integer.parseInt(request.getParameter("dataSourceId"));
		HashMap<String, Object> dMap = new HashMap<String, Object>();
		DataSource dataSource = publicService.findDataSource(id);
		List<Map<String,Object>> dataBaseName=null;
		if (dataSource != null) {
			dataBaseName = dataHandlingService.getTableName(dataSource.getUrl(), dataSource.getUser(), dataSource.getPassword(), dataSource.getCoding(), dataSource.getSourceType());
		}
		if(dataBaseName==null || dataBaseName.isEmpty()){
			dMap.put("info", "0");
		}else{
			dMap.put("info", dataBaseName);
		}
		String result = formatToJson(dMap);
		super.pringWriterToPage(result, "application/json", response);
	}
	// 获取数据库表字段信息
	@RequestMapping("DataHandlingFieldName")
	@ResponseBody
	public void toDataHandlingFieldName(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer id = Integer.parseInt(request.getParameter("dataSourceId"));
		String tableName=request.getParameter("tableName");
		HashMap<String, Object> dMap = new HashMap<String, Object>();
		DataSource dataSource = publicService.findDataSource(id);
		List<Map<String,Object>> field=null;
		if (dataSource != null) {
			field=dataHandlingService.getField(dataSource.getUrl(), dataSource.getUser(), dataSource.getPassword(), dataSource.getCoding(), dataSource.getSourceType(), tableName);
		}
		if(field==null || field.isEmpty()){
			dMap.put("info", "0");
		}else{
			dMap.put("info", field);
		}
		String result = formatToJson(dMap);
		super.pringWriterToPage(result, "application/json", response);
	}
	// 获取数据库表字段信息
	@RequestMapping("DataHandlingFileFieldName")
	@ResponseBody
	public void toDataHandlingFileFieldName(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String sourceType=request.getParameter("sourceType");
		String inPath=request.getParameter("inPath");
		String txt_type=request.getParameter("txt_type");
		String rowRegex=request.getParameter("field_field_split");
		String fieldRegex=request.getParameter("field_split");
		String sheetName=request.getParameter("sheetName");
		String elementPath=request.getParameter("elementPath");
		if(rowRegex==null || rowRegex.equals("Needn't input!")){
			rowRegex=null;
		}
		List<Map<String, String>> fieldName=null;
		HashMap<String, Object> dMap = new HashMap<String, Object>();
		if(sourceType.equals("json")){
			fieldName = dataHandlingService.getJsonField(inPath);
		}
		if(sourceType.equals("txt")){
			fieldName=dataHandlingService.getTxtField(inPath, txt_type, rowRegex, fieldRegex);
		}
		if(sourceType.equals("excel")){
			fieldName=dataHandlingService.getExcelField(inPath, sheetName);
		}
		if(sourceType.equals("xml")){
			fieldName=dataHandlingService.getXmlField(inPath, elementPath);
		}
		if(fieldName==null || fieldName.isEmpty()){
			dMap.put("info", "0");
		}else{
			dMap.put("info", fieldName);
		}
		String result = formatToJson(dMap);
		super.pringWriterToPage(result, "application/json", response);
	}
	// 获取数据库表字段信息
	@RequestMapping("DataHandlingImportSheetName")
	@ResponseBody
	public void toDataHandlingImportSheetName(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String inPath=request.getParameter("inPath");
		HashMap<String, Object> dMap = new HashMap<String, Object>();
		List<Map<String, String>> excelSheetName = dataHandlingService.getExcelSheetName(inPath);
		if(excelSheetName==null || excelSheetName.isEmpty()){
			dMap.put("info", "0");
		}else{
			dMap.put("info", excelSheetName);
		}
		String result = formatToJson(dMap);
		super.pringWriterToPage(result, "application/json", response);
	}
	// 保存信息
	@RequestMapping("dataHandlingSave")
	@ResponseBody
	public void toDataHandlingSave(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id=request.getParameter("id");
		String name=request.getParameter("name");
		String description=request.getParameter("description");
		String classid=request.getParameter("classid");
		String dataSourceId=request.getParameter("dataSourceId");
		String dataSourceType=request.getParameter("dataSourceType");
		String filePath=request.getParameter("filePath");
		String txt_type=request.getParameter("txt_type");
		String field_field_split=request.getParameter("field_field_split");
		String field_split=request.getParameter("field_split");
		String elementPath=request.getParameter("elementPath");
		String sheetName=request.getParameter("sheetName");
		String systemName=request.getParameter("systemName");
		
		String type=request.getParameter("type");
		
		String mongodb_collection=request.getParameter("mongodb_collection");
		String sql_tableName=request.getParameter("sql_tableName");
		
		String corresponding=request.getParameter("corresponding");
		User logUser = publicService.findUser((Integer) request.getSession()
				.getAttribute("userid"));
		
		DataHandling dataHandling=new DataHandling();
		dataHandling.setName(name);
		dataHandling.setDescription(description);
		dataHandling.setClassesId(classid==null?null:Integer.parseInt(classid));
		dataHandling.setDataSourceId(classid==null?null:Integer.parseInt(dataSourceId));
		dataHandling.setFilePath(filePath);
		dataHandling.setTxtType(txt_type);
		dataHandling.setFieldFieldSplit(field_field_split);
		dataHandling.setFieldSplit(field_split);
		dataHandling.setXpathPath(elementPath);
		dataHandling.setSheetName(sheetName);
		dataHandling.setCorrespondingField(corresponding);
		dataHandling.setStatus(0);
		dataHandling.setCreateUserId((Integer) request.getSession().getAttribute("userid"));
		dataHandling.setCreateTime(DateUtils.getDateTime());
		dataHandling.setSystemName(systemName);
		dataHandling.setType(Integer.parseInt(type));
		DataHandling d2=new DataHandling();
		if(dataSourceType.equals("mongodb")){
			dataHandling.setTableName(sql_tableName);
		}else{
			dataHandling.setTableName(sql_tableName);
		}
		if (id != null && !id.equals("0") && !id.equals("0") ) {
			dataHandling.setId(Integer.parseInt(id));
			DataSource logDataSource = publicService.findDataSource(Integer
					.parseInt(id));
			int logTime = 0;
			try {
				d2=dataHandlingService.editDataHandling(dataHandling);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null,
						"【" + logUser.getNickname() + "】【修改】数据导入【"
								+ logDataSource.getName() + "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null,
						"【" + logUser.getNickname() + "】【修改】数据源【"
								+ logDataSource.getName() + "】成功！修改为【" + name
								+ "】", 0);
			}
		} else if (id == null ) {
			int logTime = 0;
			try {
				d2=dataHandlingService.saveDataHandling(dataHandling);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】数据导入【" + name
						+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】数据导入【" + name + "】成功！",
						0);
			}

		}
		String result = formatToJson(d2);
		super.pringWriterToPage(result, "application/json", response);
	}
	
	@RequestMapping("DataHandlingImportDel")
	@ResponseBody
	public void toDataHandlingImportDel(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		DataHandling dataHandlingImport = new DataHandling();
		String result ="";
		XxlJobInfo jobsByParam = xxlJobInfoDao.getJobsByParam(id);
		if(jobsByParam!=null){
			result = "{\"result\":\"no\",\"msg\":\"关联任务调度,不可删除！\"}";
		}else{
			try {
				dataHandlingImport = dataHandlingService.findDataHandling(Integer.parseInt(id));
				String filePath = dataHandlingImport.getFilePath();
				if(filePath!=null){
					File file=new File(filePath);
					if(file.exists()){
						file.delete();
					}
				}
				dataHandlingService.deleteDataHandling(dataHandlingImport);
				result = "{\"result\":\"ok\",\"msg\":\"删除成功！\"}";
			} catch (Exception e) {
				result = "{\"result\":\"no\",\"msg\":\"删除失败！\"}";
			}
			
		}
		
		super.pringWriterToPage(result.toString(), "application/json", response);

	}
	/**
	 * 提交
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("DataHandlingHandle")
	@ResponseBody
	public void toDataHandlingHandle(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		DataHandling dataHandling = new DataHandling();
		dataHandling = dataHandlingService.findDataHandling(Integer.parseInt(id));
		String result = "";
		try {
			//dataHandlingService.importData(dataHandlingImport);
			result = "{\"result\":" + "\"ok\"}";
			dataHandling.setStatus(1);
			dataHandling.setSubmitTime(DateUtils.getDateTime());
			dataHandlingService.editDataHandling(dataHandling);
		} catch (Exception e) {
			result = "{\"result\":" + "\"no\"}";
		}
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	
	@RequestMapping("DataHandlingImportUpload")
	public void toDataHandlingImportUpload(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("file") CommonsMultipartFile file) throws Exception {
		HashMap<String, Object> dMap = new HashMap<String, Object>();
		String uuid="";
		String suffix="";
		//PrintWriter out;
		boolean flag = false;
		if (file.getSize() > 0) {
			String path = "/asserts/upload";
			String uploadPath = request.getSession().getServletContext()
					.getRealPath(path);
			
			suffix = file.getOriginalFilename();
			suffix=suffix.substring(suffix.lastIndexOf("."), suffix.length());
			uuid=UUID.randomUUID().toString();
			FileUtils.copyInputStreamToFile(file.getInputStream(),
					new File(uploadPath,  uuid + suffix));
			flag = true;
			suffix = uploadPath + "/" + uuid + suffix;
			System.out.println("【文件上传地址】"+suffix);
		}
		if (flag == true) {
			dMap.put("info", suffix);
		} else {
			dMap.put("info", "error");
		}
		String result = formatToJson(dMap);
		super.pringWriterToPage(result, "application/json", response);
	}
	
	//大数据仓储-数据备份
	@RequestMapping("data-handling-backup.html")
	public String dataHandlingBackup() {
		return "/modules/datahandling/data_handing_backup";
	}
	
	//大数据仓储-数据恢复
	@RequestMapping("data-handling-recovery.html")
	public String dataHandlingRecovery() {
		return "/modules/datahandling/data_handing_recovery";
	}
	//自定义，选择知识库
	@RequestMapping("data-handling-customize.html")
	public String dataHandlingCustomize() {
		return "/modules/datahandling/data_handling_customize";
	}
	//初始化数据备份页面
	@RequestMapping("initbackup")
	@ResponseBody
	public void initbackup(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		List<Classes> classes = publicService.getClasses();
		List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
		for (Classes clazz : classes) {
			Map<String, Object> m = new HashMap<String, Object>();
			HashMap<String, Object> queryParams = new HashMap<String, Object>();
			queryParams.put("=,classesEn", clazz.getNameEn());
			queryParams.put("^,createTime", "desc");
			List<DataBackup> dataBackup = publicService.getDataBackup(queryParams , 1, 2);
			String id = "0";
			if(dataBackup!=null && dataBackup.size()>0){
				id = dataBackup.get(0).getDataIdEnd();
				if(id==null && dataBackup.size()>1){
					id = dataBackup.get(1).getDataIdEnd();
				}
				m.put("dataBackup", dataBackup.get(0));
			}else{
				m.put("dataBackup", "");
			}
			/*
			Map<String, Object> conditions = new HashMap<String, Object>();
			if(id!=null){
				conditions.put(">=id", id);
			}
			Long zcount = dynamicService.getDynamicCount(clazz.getNameEn(), conditions);//增量总数
			Long count = dynamicService.getDynamicCount(clazz.getNameEn(), null);//全部总数
			m.put("zcount", zcount);
			m.put("count", count);*/
			m.put("clazz", clazz);
			listMap.add(m);
		}
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("%,classesEn", ";");
		queryParams.put("^,createTime", "desc");
		List<DataBackup> dataBackup = publicService.getDataBackup(queryParams , 1, 1);
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("customize", dataBackup);
		m.put("list", listMap);
		String result = formatToJson(m);
		super.pringWriterToPage(result, "application/json", response);
	}
	// 备份
	@RequestMapping("backup")
	@ResponseBody
	public void backup(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String classesEn = request.getParameter("classesEn");
		String allOrZeng = request.getParameter("allOrZeng");
		
		String dateTime = DateUtils.getDateTime();
		String date = DateUtils.getDate(dateTime, "yyyy-MM-dd").replace("-", "");
		String path = XxlConfClient.get("dal.file.path", "");
		path = path + "/backup";
		if(!new File(path).exists()){
			new File(path).mkdirs();
		}
		long time = System.currentTimeMillis();
		String filePath = path  + "/" + classesEn + "-" + time + "/" + classesEn + "-" + date + "-" + System.currentTimeMillis()+".xml";
		
		if(!new File(path  + "/" + classesEn + "-" + time).exists()){
			new File(path  + "/" + classesEn + "-" + time).mkdirs();
		}
		FileOutputStream out = new FileOutputStream(new File(filePath));
		TransformerHandler handler = CreateXMLFile.createXML(out);
		Long dynamicCount = dynamicService.getDynamicCount(classesEn, null);
		DataBackup db = new DataBackup();
		db.setClassesEn(classesEn);
		db.setCreateTime(DateUtils.getDateTime());
		db.setCreateUser("admin");
		db.setFilePath(path+ "/" + classesEn + "-" + time);
		db.setStatus(0);
		db.setRepositoryCount(Integer.parseInt(dynamicCount+""));
		db.setType(Integer.parseInt(allOrZeng));
		
		String startId="";
		String endId="";
		int count=0;
		if(allOrZeng.equals("0")){//全库备份
			DataBackup saveDataBackup = baseService.saveDataBackup(db);
			
			HashMap<String, Object> queryParams = new HashMap<String, Object>();
	        queryParams.put("=,classesEn", classesEn);
	        Integer shardingRepositoryCountCount = publicService.getShardingRepositoryCountCount(queryParams);
			if(!shardingRepositoryCountCount.equals(0)){//分库分表
				List<ShardingRepositoryCount> shardingRepositoryCount = publicService.getShardingRepositoryCount(queryParams, 1, shardingRepositoryCountCount);
				for (ShardingRepositoryCount src : shardingRepositoryCount) {
					List<Map<String, Object>> l = dynamicService.getDynamicData(classesEn, "0", 50000, src.getShardingDataSourceId()+"", src.getTableName());
					while(l.size()>0){
						startId = l.get(0).get("id")+"";
						endId = l.get(l.size()-1).get("id")+"";
						System.out.println("============备份开始id:"+startId+"\t备份结束id:"+endId+"============");
						CreateXMLFile.writeToXml(handler, l);
						if(new File(filePath).length()/1024/1024>500){
							filePath = path + "/" + classesEn + "-" + time + "/" + classesEn + "-" + date + "-" + System.currentTimeMillis()+".xml";
							CreateXMLFile.closeXml(handler,out);
							out = new FileOutputStream(new File(filePath));
							handler = CreateXMLFile.createXML(out);
						}
						count = count + l.size();
						l = dynamicService.getDynamicData(classesEn,  l.get(l.size()-1).get("id")+"", 50000, src.getShardingDataSourceId()+"", src.getTableName());
					}
				}
			}else{
				List<Map<String, Object>> l = dynamicService.getDynamicData(classesEn, "0", 50000);
				while(l.size()>0){
					startId = l.get(0).get("id")+"";
					endId = l.get(l.size()-1).get("id")+"";
					System.out.println("============备份开始id:"+startId+"\t备份结束id:"+endId+"============");
					CreateXMLFile.writeToXml(handler, l);
					if(new File(filePath).length()/1024/1024>500){
						filePath = path + "/" + classesEn + "-" + time + "/" + classesEn + "-" + date + "-" + System.currentTimeMillis()+".xml";
						CreateXMLFile.closeXml(handler,out);
						out = new FileOutputStream(new File(filePath));
						handler = CreateXMLFile.createXML(out);
					}
					count = count + l.size();
					l = dynamicService.getDynamicData(classesEn, l.get(l.size()-1).get("id")+"", 50000);
				}
			}
			/*
			filePath = path + "/" + classesEn + "-" + date + "-" + System.currentTimeMillis()+"";
			if(!new File(filePath).exists()){//创建文件夹
				new File(filePath).mkdirs();
			}
			*/
			//将文件复制到文件加下
			//for (int i = 0; i < files.size(); i++) {
				//FileUtils.copyFileToDirectory(new File(files.get(i)), new File(filePath));
			//}
			//FileUtils.copyDirectoryToDirectory(srcDir, filePath);
			
			//这里是压缩程序
			CreateXMLFile.closeXml(handler,out);
			
			FileTool.zip(path + "/" + classesEn + "-" + time,path + "/" + classesEn + "-" + time+".zip");
			FileUtils.deleteDirectory(new File(path + "/" + classesEn + "-" + time));
			//FileUtils.forceDeleteOnExit(new File(path + "/" + classesEn + "-" + time));
			
			saveDataBackup.setBackupCount(count);
			saveDataBackup.setFilePath(path + "/" + classesEn + "-" + time+".zip");
			saveDataBackup.setDataIdEnd(endId);
			saveDataBackup.setDataIdStart(startId);
			saveDataBackup.setStatus(1);
			DataBackup editDataBackup = baseService.editDataBackup(saveDataBackup);
			
			System.out.println("备份完成！");
		}else{//增量备份
			HashMap<String, Object> queryParams = new HashMap<String, Object>();
			queryParams.put("=,classesEn", classesEn);
			queryParams.put("^,createTime", "desc");
			List<DataBackup> dataBackup = publicService.getDataBackup(queryParams , 1, 1);
			String id = "0";
			if(dataBackup != null && dataBackup.size() > 0){
				id = dataBackup.get(0).getDataIdEnd();
			}
			DataBackup saveDataBackup = baseService.saveDataBackup(db);
			
			queryParams = new HashMap<String, Object>();
	        queryParams.put("=,classesEn", classesEn);
	        Integer shardingRepositoryCountCount = publicService.getShardingRepositoryCountCount(queryParams);
			if(!shardingRepositoryCountCount.equals(0)){//分库分表
				List<ShardingRepositoryCount> shardingRepositoryCount = publicService.getShardingRepositoryCount(queryParams, 1, shardingRepositoryCountCount);
				for (ShardingRepositoryCount src : shardingRepositoryCount) {
					List<Map<String, Object>> l = dynamicService.getDynamicData(classesEn, "0", 50000, src.getShardingDataSourceId()+"", src.getTableName());
					while(l.size()>0){
						startId = l.get(0).get("id")+"";
						endId = l.get(l.size()-1).get("id")+"";
						System.out.println("============备份开始id:"+startId+"\t备份结束id:"+endId+"============");
						if(new File(filePath).length()/1024/1024>500){
							filePath = path + "/" + classesEn + "-" + time + "/" + classesEn + "-" + date + "-" + System.currentTimeMillis()+".xml";
							CreateXMLFile.closeXml(handler,out);
							out = new FileOutputStream(new File(filePath));
							handler = CreateXMLFile.createXML(out);
						}
						CreateXMLFile.writeToXml(handler, l);
						count = count + l.size();
						l = dynamicService.getDynamicData(classesEn, l.get(l.size()-1).get("id")+"", 50000, src.getShardingDataSourceId()+"", src.getTableName());
					}
				}
			}else{
				List<Map<String, Object>> l = dynamicService.getDynamicData(classesEn, id, 50000);
				while(l.size()>0){
					startId = l.get(0).get("id")+"";
					endId = l.get(l.size()-1).get("id")+"";
					System.out.println("============备份开始id:"+startId+"\t备份结束id:"+endId+"============");
					if(new File(filePath).length()/1024/1024>500){
						filePath = path + "/" + classesEn + "-" + time + "/" + classesEn + "-" + date + "-" + System.currentTimeMillis()+".xml";
						CreateXMLFile.closeXml(handler,out);
						out = new FileOutputStream(new File(filePath));
						handler = CreateXMLFile.createXML(out);
					}
					CreateXMLFile.writeToXml(handler, l);
					count = count + l.size();
					l = dynamicService.getDynamicData(classesEn, l.get(l.size()-1).get("id")+"", 50000);
				}
			}
			/*
			filePath = filePath + "/" + classesEn + "-" + date + "-" + System.currentTimeMillis()+"";
			if(!new File(filePath).exists()){//创建文件夹
				new File(filePath).mkdirs();
			}
			//将文件复制到文件加下
			for (int i = 0; i < files.size(); i++) {
				FileUtils.copyFileToDirectory(new File(files.get(i)), new File(filePath));
			}
			*/
			CreateXMLFile.closeXml(handler,out);
			//这里是压缩程序
			FileTool.zip(path + "/" + classesEn + "-" + time,path + "/" + classesEn + "-" + time+".zip");
			FileUtils.deleteDirectory(new File(path + "/" + classesEn + "-" + time));
			//FileUtils.forceDeleteOnExit(new File(path + "/" + classesEn + "-" + time));
			saveDataBackup.setBackupCount(count);
			saveDataBackup.setDataIdEnd(endId);
			saveDataBackup.setFilePath(path + "/" + classesEn + "-" + time+".zip");
			saveDataBackup.setDataIdStart(startId);
			saveDataBackup.setStatus(1);
			DataBackup editDataBackup = baseService.editDataBackup(saveDataBackup);
			System.out.println("备份完成！");
		}
		String result = formatToJson("[{\"info\":\"success\"}]");
		super.pringWriterToPage(result, "application/json", response);
	}
	// 备份下载
	@RequestMapping("downBackup")
	@ResponseBody
	public void downBackup(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String filePath = request.getParameter("filePath");
		/*
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("=,classesEn", classesEn);
		queryParams.put("^,createTime", "desc");
		List<DataBackup> dataBackup = publicService.getDataBackup(queryParams , 1, 1);
		*/
		String path = filePath;
		path = path.replace("\\", "/");
		System.out.println("下载路径："+path);
		// 设置响应头，控制浏览器下载该文件
		String filename = path.substring(path.lastIndexOf("/")+1, path.length());
//		FileDownloadUtil.download("D:\\"+path, filename, request, response);
		
		filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
		response.setHeader("content-disposition","attachment;filename=" + filename + "");
//		response.setContentType("application/octet-stream");
		response.setContentType("application/OCTET-STREAM;charset=UTF-8");
		// 读取要下载的文件，保存到文件输入流
		FileInputStream in = new FileInputStream(path);
		// 创建输出流
		OutputStream out = response.getOutputStream();
		// 创建缓冲区
		byte buffer[] = new byte[1024];
		int len = 0;
		// 循环将输入流中的内容读取到缓冲区当中
		while ((len = in.read(buffer)) > 0) {
			// 输出缓冲区的内容到浏览器，实现文件下载
			out.write(buffer, 0, len);
		}
		// 关闭文件输入流
		in.close();
		// 关闭输出流
		out.close();
	}
	//初始化数据恢复页面
	@RequestMapping("initrecovery")
	@ResponseBody
	public void initRecovery(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		List<Classes> classes = publicService.getClasses();
		List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
		for (Classes clazz : classes) {
			Map<String, Object> m = new HashMap<String, Object>();
			HashMap<String, Object> queryParams = new HashMap<String, Object>();
			queryParams.put("=,classesEn", clazz.getNameEn());
			queryParams.put("^,createTime", "desc");
			List<DataRecovery> dataBackup = publicService.getDataRecovery(queryParams , 1, 1);
			if(dataBackup!=null && dataBackup.size()>0){
				m.put("dataRecovery", dataBackup.get(0));
			}else{
				m.put("dataRecovery", "");
			}
			m.put("clazz", clazz);
			listMap.add(m);
		}
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("%,classesEn", ";");
		queryParams.put("^,createTime", "desc");
		List<DataRecovery> dataRecovery = publicService.getDataRecovery(queryParams , 1, 1);
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("customize", dataRecovery);
		m.put("list", listMap);
		String result = formatToJson(m);
		super.pringWriterToPage(result, "application/json", response);
	}
	//上传恢复文件
	@RequestMapping(value = "/uploadRecovery", method = RequestMethod.POST)
	public void uploadRecovery(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("file") CommonsMultipartFile file) throws Exception {
		HashMap<String, Object> dMap = new HashMap<String, Object>();
		String classesEn = request.getParameter("classesEn");
		String filename="";
		String suffix="";
		String filePath = XxlConfClient.get("dal.file.path", "");
		boolean flag = false;
		if (file.getSize() > 0) {
			String dateTime = DateUtils.getDateTime();
			System.out.println(dateTime);
			String date = DateUtils.getDate(dateTime, "yyyy-MM-dd").replace("-", "");
			filePath = filePath + "/recovery";
			if(!new File(filePath).exists()){
				new File(filePath).mkdirs();
			}
			if(classesEn.equals("cus")){
				filename =  file.getOriginalFilename().split("-")[0] + "-" + date + "-" + System.currentTimeMillis();
			}else{
				filename =  classesEn + "-" + date + "-" + System.currentTimeMillis();
			}
			//String path = "/asserts/upload";
			//String uploadPath = request.getSession().getServletContext().getRealPath(path);
			suffix = file.getOriginalFilename();
			suffix=suffix.substring(suffix.lastIndexOf("."), suffix.length());
			FileUtils.copyInputStreamToFile(file.getInputStream(),
					new File(filePath,  filename + suffix));
			flag = true;
			filePath = filePath + "/" + filename + suffix;
			System.out.println("【文件上传地址】"+filePath);
		}
		if (flag == true) {
			dMap.put("info", filePath);
		} else {
			dMap.put("info", "error");
		}
		String result = formatToJson(dMap);
		super.pringWriterToPage(result, "application/json", response);
	}
	//数据恢复
	@RequestMapping("recovery")
	@ResponseBody
	public void recovery(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String filePath = request.getParameter("filePath");
		String classesEn = request.getParameter("classesEn");
		
		String path = filePath.substring(0, filePath.lastIndexOf("."));
		FileTool.deCompress(filePath,path,true);//解压缩
		FileUtils.forceDelete(new File(filePath));//删除压缩包
		
		File files = new File(path);
    	File[] listFiles = files.listFiles();
		
		DataRecovery recovery = new DataRecovery();
		recovery.setClassesEn(classesEn);
		recovery.setCreateTime(DateUtils.getDateTime());
		recovery.setCreateUser("admin");
		recovery.setFilePath(path);
		recovery.setStatus(0);
		DataRecovery saveDataRecovery = baseService.saveDataRecovery(recovery);
		int count = 0;
		for (int i = 0; i < listFiles.length; i++) {
			System.out.println(">>>开始恢复文件："+listFiles[i]);
			Map<String, String> dataRecovery = dataHandlingService.dataRecovery(classesEn, listFiles[i].getAbsolutePath());
			if(dataRecovery.get("count")!=null && !"".equals(dataRecovery.get("count"))
					&& dataRecovery.get("startId")!=null && !"".equals(dataRecovery.get("startId"))
					&& dataRecovery.get("endId")!=null && !"".equals(dataRecovery.get("endId"))){
				count += Integer.parseInt(dataRecovery.get("count"));
				if(i == 0){
					saveDataRecovery.setDataIdStart(dataRecovery.get("startId"));
				}
				if(i == listFiles.length-1){
					saveDataRecovery.setDataIdEnd(dataRecovery.get("endId"));
					saveDataRecovery.setRecoveryCount(count);
					Long dynamicCount = dynamicService.getDynamicCount(classesEn, null);
					saveDataRecovery.setRepositoryCount(dynamicCount.intValue());
					saveDataRecovery.setStatus(1);
					DataRecovery editDataRecovery = baseService.editDataRecovery(saveDataRecovery);
				}
			}
		}
		System.out.println(">>>恢复成功！");
		String result = formatToJson("[{\"info\":\"success\"}]");
		super.pringWriterToPage(result, "application/json", response);
	}
	//备份列表
	@RequestMapping("backupList")
	@ResponseBody
	public void backupList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
		Integer pageSize = Integer.parseInt(request.getParameter("page"));
		String queryParam = request.getParameter("queryParams");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if(queryParam != null && !"".equals(queryParam) && !"-1".equals(queryParam)){//说明是全部
			queryParams.put("=,classesEn", queryParam);
		}
		queryParams.put("^,createTime", "desc");
		Integer count = publicService.getDataBackupCount(queryParams);
		List<DataBackup> list = publicService.getDataBackup(queryParams,pageSize, pageNumber);
		List<Classes> classes = publicService.getClasses();

		int listsize = list==null?0:list.size();
		StringBuffer sb = new StringBuffer();
		sb.append("{\"listsize\":" + listsize + ",");
		sb.append("\"pageSize\":"
				+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"result\":" +formatToJson(list)+",");
		sb.append("\"classes\":" +formatToJson(classes));
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}
	//恢复列表
	@RequestMapping("recoveryList")
	@ResponseBody
	public void recoveryList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
		Integer pageSize = Integer.parseInt(request.getParameter("page"));
		String queryParam = request.getParameter("queryParams");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if(queryParam != null && !"".equals(queryParam) && !"-1".equals(queryParam)){//说明是全部
			queryParams.put("=,classesEn", queryParam);
		}
		queryParams.put("^,createTime", "desc");
		Integer count = publicService.getDataRecoveryCount(queryParams);
		List<DataRecovery> list = publicService.getDataRecovery(queryParams,pageSize, pageNumber);
		List<Classes> classes = publicService.getClasses();

		int listsize = list==null?0:list.size();
		StringBuffer sb = new StringBuffer();
		sb.append("{\"listsize\":" + listsize + ",");
		sb.append("\"pageSize\":"
				+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"result\":" +formatToJson(list)+",");
		sb.append("\"classes\":" +formatToJson(classes));
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}
	//知识库
	@RequestMapping("getClasses")
	@ResponseBody
	public void getClasses(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String classesIds = request.getParameter("classesIds");
		String[] split = classesIds.split(",");
		List<Classes> l = new ArrayList<Classes>();
		for (String s : split) {
			Classes clazz = publicService.findClasses(Integer.parseInt(s));
			l.add(clazz);
		}
		String result = super.formatToJson(l);
		super.pringWriterToPage(result, "application/json", response);
	}
	//自定义备份
	@RequestMapping("customize")
	@ResponseBody
	public void customize(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String classesIds = request.getParameter("classesIds");
		String allOrZeng = request.getParameter("allOrZeng");
		
		String[] split = classesIds.split(",");
		String classEn = "";
		for (String s : split) {
			Classes clazz = publicService.findClasses(Integer.parseInt(s));
			classEn += clazz.getNameEn() + ";";
		}
		DataBackup dbCustomize = new DataBackup();
		dbCustomize.setCreateTime(DateUtils.getDateTime());
		dbCustomize.setCreateUser("admin");
		dbCustomize.setStatus(0);
		dbCustomize.setClassesEn(classEn);
		dbCustomize.setType(Integer.parseInt(allOrZeng));
		DataBackup saveCustomizeDataBack = baseService.saveDataBackup(dbCustomize);
		
		String classNameEn = "";
		List<String> paths =new ArrayList<String>();
		String path = XxlConfClient.get("dal.file.path", "");
		path = path + "/backup";
		if(!new File(path).exists()){
			new File(path).mkdirs();
		}
		
		for (String s : split) {
			Classes clazz = publicService.findClasses(Integer.parseInt(s));
			classNameEn += clazz.getNameEn()+"_";
			String classesEn = clazz.getNameEn();
			String dateTime = DateUtils.getDateTime();
			String date = DateUtils.getDate(dateTime, "yyyy-MM-dd").replace("-", "");
			long time = System.currentTimeMillis();
			String filePath=path + "/" + classesEn + "-"+ time + "/" + classesEn + "-" + date + "-" + System.currentTimeMillis()+".xml";
			//String filePath = path + "/" + fileName;
			if(!new File(path + "/" + classesEn + "-"+ time ).exists()){
				new File(path + "/" + classesEn + "-"+ time ).mkdirs();
			}
			paths.add(path + "/" + classesEn + "-"+ time);
			FileOutputStream out = new FileOutputStream(new File(filePath));
			TransformerHandler handler = CreateXMLFile.createXML(out);
			Long dynamicCount = dynamicService.getDynamicCount(classesEn, null);
			DataBackup db = new DataBackup();
			db.setClassesEn(classesEn);
			db.setCreateTime(DateUtils.getDateTime());
			db.setCreateUser("admin");
			db.setFilePath(path + "/" + classesEn + "-"+ time);
			db.setStatus(0);
			db.setRepositoryCount(Integer.parseInt(dynamicCount+""));
			db.setType(Integer.parseInt(allOrZeng));
			String startId="";
			String endId="";
			int count=0;
			if(allOrZeng.equals("0")){//全库备份
				DataBackup saveDataBackup = baseService.saveDataBackup(db);
				
				HashMap<String, Object> queryParams = new HashMap<String, Object>();
		        queryParams.put("=,classesEn", classesEn);
		        Integer shardingRepositoryCountCount = publicService.getShardingRepositoryCountCount(queryParams);
				if(!shardingRepositoryCountCount.equals(0)){//分库分表
					List<ShardingRepositoryCount> shardingRepositoryCount = publicService.getShardingRepositoryCount(queryParams, 1, shardingRepositoryCountCount);
					for (ShardingRepositoryCount src : shardingRepositoryCount) {
						List<Map<String, Object>> l = dynamicService.getDynamicData(classesEn, "0", 50000, src.getShardingDataSourceId()+"", src.getTableName());
						while(l.size()>0){
							startId = l.get(0).get("id")+"";
							endId = l.get(l.size()-1).get("id")+"";
							System.out.println("============备份开始id:"+startId+"\t备份结束id:"+endId+"============");
							if(new File(filePath).length()/1024/1024>500){
								filePath = path + "/" + classesEn + "-"+ time + "/" + classesEn + "-" + date + "-" + System.currentTimeMillis()+".xml";
								//paths.add(filePath);
								CreateXMLFile.closeXml(handler,out);
								out = new FileOutputStream(new File(filePath));
								handler = CreateXMLFile.createXML(out);
							}
							CreateXMLFile.writeToXml(handler, l);
							count = count + l.size();
							l = dynamicService.getDynamicData(classesEn,  l.get(l.size()-1).get("id")+"", 50000, src.getShardingDataSourceId()+"", src.getTableName());
						}
					}
				}else{
					List<Map<String, Object>> l = dynamicService.getDynamicData(classesEn, "0", 50000);
					while(l.size()>0){
						startId = l.get(0).get("id")+"";
						endId = l.get(l.size()-1).get("id")+"";
						System.out.println("============备份开始id:"+startId+"\t备份结束id:"+endId+"============");
						if(new File(filePath).length()/1024/1024>500){
							filePath = path + "/" + classesEn + "-"+ time + "/" + classesEn + "-" + date + "-" + System.currentTimeMillis()+".xml";
							//paths.add(filePath);
							CreateXMLFile.closeXml(handler,out);
							out = new FileOutputStream(new File(filePath));
							handler = CreateXMLFile.createXML(out);
						}
						CreateXMLFile.writeToXml(handler, l);
						count = count + l.size();
						l = dynamicService.getDynamicData(classesEn, l.get(l.size()-1).get("id")+"", 50000);
					}
				}
				
				CreateXMLFile.closeXml(handler,out);
				saveDataBackup.setBackupCount(count);
				saveDataBackup.setDataIdEnd(endId);
				saveDataBackup.setDataIdStart(startId);
				saveDataBackup.setStatus(1);
				DataBackup editDataBackup = baseService.editDataBackup(saveDataBackup);
			}else{//增量备份
				HashMap<String, Object> queryParams = new HashMap<String, Object>();
				queryParams.put("=,classesEn", classesEn);
				queryParams.put("^,createTime", "desc");
				List<DataBackup> dataBackup = publicService.getDataBackup(queryParams , 1, 1);
				String id = "0";
				if(dataBackup != null && dataBackup.size() > 0){
					id = dataBackup.get(0).getDataIdEnd();
				}
				DataBackup saveDataBackup = baseService.saveDataBackup(db);
				
				
				queryParams = new HashMap<String, Object>();
		        queryParams.put("=,classesEn", classesEn);
		        Integer shardingRepositoryCountCount = publicService.getShardingRepositoryCountCount(queryParams);
				if(!shardingRepositoryCountCount.equals(0)){//分库分表
					List<ShardingRepositoryCount> shardingRepositoryCount = publicService.getShardingRepositoryCount(queryParams, 1, shardingRepositoryCountCount);
					for (ShardingRepositoryCount src : shardingRepositoryCount) {
						List<Map<String, Object>> l = dynamicService.getDynamicData(classesEn, "0", 50000, src.getShardingDataSourceId()+"", src.getTableName());
						while(l.size()>0){
							startId = l.get(0).get("id")+"";
							endId = l.get(l.size()-1).get("id")+"";
							System.out.println("============备份开始id:"+startId+"\t备份结束id:"+endId+"============");
							if(new File(filePath).length()/1024/1024>500){
								filePath = path + "/" + classesEn + "-"+ time + "/" + classesEn + "-" + date + "-" + System.currentTimeMillis()+".xml";
								//paths.add(filePath);
								CreateXMLFile.closeXml(handler,out);
								out = new FileOutputStream(new File(filePath));
								handler = CreateXMLFile.createXML(out);
							}
							CreateXMLFile.writeToXml(handler, l);
							count = count + l.size();
							l = dynamicService.getDynamicData(classesEn, l.get(l.size()-1).get("id")+"", 50000, src.getShardingDataSourceId()+"", src.getTableName());
						}
					}
				}else{
					List<Map<String, Object>> l = dynamicService.getDynamicData(classesEn, id, 50000);
					while(l.size()>0){
						startId = l.get(0).get("id")+"";
						endId = l.get(l.size()-1).get("id")+"";
						System.out.println("============备份开始id:"+startId+"\t备份结束id:"+endId+"============");
						if(new File(filePath).length()/1024/1024>500){
							filePath = path + "/" + classesEn + "-"+ time + "/" + classesEn + "-" + date + "-" + System.currentTimeMillis()+".xml";
							//paths.add(filePath);
							CreateXMLFile.closeXml(handler,out);
							out = new FileOutputStream(new File(filePath));
							handler = CreateXMLFile.createXML(out);
						}
						CreateXMLFile.writeToXml(handler, l);
						count = count + l.size();
						l = dynamicService.getDynamicData(classesEn, l.get(l.size()-1).get("id")+"", 50000);
					}
				}
				
				CreateXMLFile.closeXml(handler,out);
				saveDataBackup.setBackupCount(count);
				saveDataBackup.setDataIdEnd(endId);
				saveDataBackup.setDataIdStart(startId);
				saveDataBackup.setStatus(1);
				DataBackup editDataBackup = baseService.editDataBackup(saveDataBackup);
			}
			System.out.println("备份完成！");
		}
		//以下进行压缩
		String dateTime = DateUtils.getDateTime();
		String date = DateUtils.getDate(dateTime, "yyyy-MM-dd").replace("-", "");
		String filePath = path + "/" + classNameEn.substring(0,classNameEn.lastIndexOf("_")) + "-" + date + "-" + System.currentTimeMillis();
		if(!new File(filePath).exists()){//创建文件夹
			new File(filePath).mkdirs();
		}
		//将文件复制到文件加下
		for (int i = 0; i < paths.size(); i++) {
			//FileUtils.copyFileToDirectory(new File(paths.get(i)), new File(filePath));
			FileUtils.moveDirectoryToDirectory(new File(paths.get(i)), new File(filePath),true);
			//FileUtils.moveDirectoryToDirectory(src, destDir, createDestDir);
		}
		//这里是压缩程序
		FileTool.zip(filePath,filePath+".zip");
		FileUtils.deleteDirectory(new File(filePath));
		saveCustomizeDataBack.setFilePath(filePath+".zip");
		saveCustomizeDataBack.setStatus(1);
		DataBackup editCustomizeDataBackup = baseService.editDataBackup(saveCustomizeDataBack);
		String result = formatToJson("[{\"info\":\"success\"}]");
		super.pringWriterToPage(result, "application/json", response);
	}
	//数据自定义恢复
	@RequestMapping("customizeRecovery")
	@ResponseBody
	public void customizeRecovery(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String filePath = request.getParameter("filePath");
		String path = filePath.substring(0, filePath.lastIndexOf("."));
		FileTool.deCompress(filePath,path,true);//解压缩
		FileUtils.forceDelete(new File(filePath));//删除压缩包
		
		File files = new File(path);
    	File[] listFiles = files.listFiles();
    	String classsesEns = "";
    	for (File file : listFiles) {
    		String classesEn = file.getName().split("-")[0];
    		classsesEns += classesEn + ";";
    	}
		
		DataRecovery customizeRecovery = new DataRecovery();
		customizeRecovery.setCreateTime(DateUtils.getDateTime());
		customizeRecovery.setCreateUser("admin");
		customizeRecovery.setFilePath(path);
		customizeRecovery.setStatus(0);
		customizeRecovery.setClassesEn(classsesEns);
		DataRecovery saveCustomizeDataRecovery = baseService.saveDataRecovery(customizeRecovery);
		
    	for (File file : listFiles) {//文件夹
    		
    		String classesEn = file.getName().split("-")[0];
    		DataRecovery recovery = new DataRecovery();
    		recovery.setClassesEn(classesEn);
    		recovery.setCreateTime(DateUtils.getDateTime());
    		recovery.setCreateUser("admin");
    		recovery.setFilePath(file.getAbsolutePath());
    		recovery.setStatus(0);
    		DataRecovery saveDataRecovery = baseService.saveDataRecovery(recovery);
    		
    		File[] lf = file.listFiles();
    		int count = 0;
    		for (int i = 0; i < lf.length; i++) {
    			System.out.println(">>>恢复文件："+lf[i]);
    			Map<String, String> dataRecovery = dataHandlingService.dataRecovery(classesEn, lf[i].getAbsolutePath());
    			if(dataRecovery.get("count")!=null && !"".equals(dataRecovery.get("count"))
    					&& dataRecovery.get("startId")!=null && !"".equals(dataRecovery.get("startId"))
    					&& dataRecovery.get("endId")!=null && !"".equals(dataRecovery.get("endId"))){
    				
    				count += Integer.parseInt(dataRecovery.get("count"));
    				if(i == 0){
    					saveDataRecovery.setDataIdStart(dataRecovery.get("startId"));
    				}
    				if(i == lf.length-1){
    					saveDataRecovery.setDataIdEnd(dataRecovery.get("endId"));
    					saveDataRecovery.setRecoveryCount(count);
    					Long dynamicCount = dynamicService.getDynamicCount(classesEn, null);
    					saveDataRecovery.setRepositoryCount(dynamicCount.intValue());
    					saveDataRecovery.setStatus(1);
    					DataRecovery editDataRecovery = baseService.editDataRecovery(saveDataRecovery);
    				}
    			}
    		}
		}
    	System.out.println(">>>恢复完成！");
    	saveCustomizeDataRecovery.setStatus(1);
    	DataRecovery editDataRecovery = baseService.editDataRecovery(saveCustomizeDataRecovery);
		String result = formatToJson("[{\"info\":\"success\"}]");
		super.pringWriterToPage(result, "application/json", response);
	}
}
